<?php
// +----------------------------------------------------------------------
// | Yzncms [ 御宅男工作室 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://yzncms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 御宅男 <530765310@qq.com>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 订单管理
// +----------------------------------------------------------------------
namespace app\cms\controller;

use think\Exception;

class Order extends Cmsbase
{
    protected $noNeedLogin = ['epay'];
    protected $noNeedRight = [];

    //创建订单并发起支付请求
    public function submit()
    {
        if (!$this->auth->isLogin()) {
            $this->error('请先登录！', url('member/index/login'));
        }
        $catid    = $this->request->param('catid/d');
        $id       = $this->request->param('id/d');
        $pay_type = $this->request->param('pay_type');
        try {
            $res = \app\cms\model\Order::submitOrder($catid, $id, $pay_type ? $pay_type : 'wechat');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        if ($res) {
            $this->success('支付成功');
        }
    }

    //企业支付通知和回调
    public function epay()
    {
        $type     = $this->request->param('type');
        $pay_type = $this->request->param('pay_type');
        if ($type == 'notify') {
            $pay = \addons\pay\library\Service::checkNotify($pay_type);
            if (!$pay) {
                echo '签名错误';
                return;
            }
            try {
                $data      = $pay->verify();
                $payamount = $pay_type == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
                \app\cms\model\Order::settle($data['out_trade_no'], $payamount);
            } catch (Exception $e) {
                //写入日志
                // $e->getMessage();
            }
            return $pay->success()->send();
        } else {
            $pay = \addons\pay\library\Service::checkReturn($pay_type);
            if (!$pay) {
                $this->error('签名错误');
            }
            if ($pay === true) {
                //微信支付
                $data = ['out_trade_no' => $this->request->param('trade_sn')];
            } else {
                $data = $pay->verify();
            }
            $order = \app\cms\model\Order::getByTradeSn($data['out_trade_no']);
            if (!$order) {
                $this->error('订单不存在!');
            }
            //你可以在这里定义你的提示信息,但切记不可在此编写逻辑
            $this->success("恭喜你！支付成功!", buildContentUrl($order['catid'], $order['contentid'], '', true, true));
        }
        return;
    }
}
